package com.decent.util;

import com.alibaba.fastjson.JSONObject;
import com.decent.dto.CouponStockDTO;
import com.decent.entity.common.TestInfoEntity;
import com.decent.dto.ResponseDTO;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.util.DigestUtils;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

/**
 * @Author decent
 * @Create 2021/3/31 - 13:11
 * @Description
 */
public class HttpUtil {
    /**
     * 发送post请求
     *
     * @param param BasicNameValuePair param1 = new BasicNameValuePair("supId", entity.getSupId() + "");
     * @param url
     * @return
     */
    public static String sendPost(List<BasicNameValuePair> param, String url) {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        String entityStr = null;
        CloseableHttpResponse response = null;
        try {
            HttpPost httpPost = new HttpPost(url);

            List<NameValuePair> list = new LinkedList<>(param);

            UrlEncodedFormEntity entityParam = new UrlEncodedFormEntity(list, "UTF-8");
            httpPost.setEntity(entityParam);
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
            response = httpClient.execute(httpPost);
            HttpEntity entity1 = response.getEntity();
            entityStr = EntityUtils.toString(entity1, "UTF-8");
        } catch (ClientProtocolException e) {
            System.err.println("Http协议出现问题");
            e.printStackTrace();
        } catch (ParseException e) {
            System.err.println("解析错误");
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("IO异常");
            e.printStackTrace();
        } finally {
            // 释放连接
            if (null != response) {
                try {
                    response.close();
                    httpClient.close();
                } catch (IOException e) {
                    System.err.println("释放连接出错");
                    e.printStackTrace();
                }
            }
        }

        // 打印响应内容
        System.out.println(entityStr);
        return entityStr;
    }

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url 发送请求的URL
     *            <p>
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url) {
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result.toString();
    }

    /**
     * 卡券购买接口
     *
     * @param entity
     * @param count
     * @return
     */
    public static String orderPay(TestInfoEntity entity, String goodsNo, Integer count) {
        String appId = entity.getAccount();
        long timestamp = System.currentTimeMillis();
        String userOrderNo = RandomCodeUtil.uuid();

        String key = entity.getGoodsSecretKey();

        String url = entity.getAddress() + entity.getCouponPay();

        String param = "app_id=" + appId + "&count=" + count
                + "&goods_no=" + goodsNo + "&timestamp=" + timestamp
                + "&user_order_no=" + userOrderNo + "&key=" + key;

        String sign = DigestUtils.md5DigestAsHex(param.getBytes()).toUpperCase();

        String http = String.format(url + "?" +
                        "app_id=%s&count=%d&goods_no=%s&timestamp=%d&user_order_no=%s&sign=%s",
                appId, count, goodsNo, timestamp, userOrderNo, sign);

        System.out.println(http);
        return HttpUtil.sendGet(http);
    }

    /**
     * 卡券产品库存查询
     *
     * @param entity
     * @param goodsNo
     */
    public static Integer getStock(TestInfoEntity entity, String goodsNo) {

        String appId = entity.getAccount();
        long timestamp = System.currentTimeMillis();

        String key = entity.getGoodsSecretKey();

        String url = entity.getAddress() + entity.getCouponStock();

        String param = "app_id=" + appId + "&goods_no=" + goodsNo
                + "&timestamp=" + timestamp
                + "&key=" + key;

        String sign = DigestUtils.md5DigestAsHex(param.getBytes()).toUpperCase();

        String http = String.format(url + "?"
                        + "app_id=%s&goods_no=%s&timestamp=%d&sign=%s",
                appId, goodsNo, timestamp, sign);

        System.out.println(http);
        String s = HttpUtil.sendGet(http);
        System.out.println(s);

        ResponseDTO responseEntity = JSONObject.parseObject(s, ResponseDTO.class);
        if (responseEntity.getData() == null) {
            return -1;
        }
        CouponStockDTO couponStockDTO = JSONObject.parseObject(responseEntity.getData().toString(), CouponStockDTO.class);
        return couponStockDTO.getStockNum();
    }


    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url 发送请求的 URL
     * @param map map
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, HashMap<String, Object> map) {
        try {
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;
            try {
                ObjectMapper objectMapper = new ObjectMapper();

                HttpPost httpPost = new HttpPost(url);
                httpPost.setHeader("Content-Type", "application/json");
                httpPost.setEntity(new StringEntity(objectMapper.writeValueAsString(map),
                        ContentType.create("text/json", "UTF-8")));

                client = HttpClients.createDefault();
                response = client.execute(httpPost);
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity);
                System.out.println(result);
                return result;
            } finally {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

}
